<?php

namespace App\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\UserRepository;
use App\User;
use App\Models\FinancialDetails;

/**
 * Class AdminUserRepositoryEloquent
 * @package namespace App\Repositories;
 */
class UserRepositoryEloquent extends BaseRepository implements UserRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return User::class;
    }

    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }

    /**
     * Store user
     * @param array $payload
     * @return bool
     */
    public function store($payload = [])
    {
        $now = \Carbon\Carbon::now()->toDateTimeString();
        $id = $this->model->insertGetId([
            'name' => $payload['name'],
            'email' => $payload['email'],
            'password' => bcrypt($payload['password']),
            'created_at'=>$now
        ]);

        if(!$id) {
            return false;
        }

        if($id && ($roles = array_get($payload, 'roles'))) {
            $this->attachRoles($id, $roles);
        }
        return true;
    }

    /**
     * update admin user
     * @param array $attributes
     * @param $id
     * @return array
     */
    public function update(array $attributes, $id)
    {
        $isAble = $this->model->where('id', '<>', $id)->where('name', $attributes['name'])->count();
        if($isAble) {
            return [
                'status' => false,
                'msg' => '用户名已被使用'
            ];
        }

        $isAble = $this->model->where('id', '<>', $id)->where('mobile', $attributes['mobile'])->count();
        if($isAble) {
            return [
                'status' => false,
                'msg' => '手机号码已被使用'
            ];
        }

        $data = [];
        if($attributes['password']) {
            $data['password'] = bcrypt($attributes['password']);
        }
        $data['name'] = $attributes['name'];
        $data['mobile'] = $attributes['mobile'];
        $result = parent::update($data, $id);
        if(!$result) {
            return [
                'status' => false,
                'msg' => '用户更新失败'
            ];
        }
        $this->model->find($id)->roles()->detach();
        //dd($attributes['roles']);
        if(isset($attributes['roles'])) {
            $this->attachRoles($id, $attributes['roles']);
        }
        return ['status' => true];
    }

    /**
     * delete admin user
     * @param $id
     * @return bool|int
     */
    public function delete($id)
    {
        $user = $this->model->find($id);

        if(!$user || $user->is_super) {
            return false;
        }
        //dd($user);
        $user->detachAllRoles();
        $user->detachAllPermissions();
        return parent::delete($id);
    }

    /**
     * Attach user roles by user id
     * @param $userId
     * @param $roles
     */
    public function attachRoles($userId, $roles)
    {
        $user = $this->model->find($userId);
        $user->attachRole($roles);
    }

     /**
     * get role's permissions
     * @param $id
     * @return array
     */
    public function rolePermissions2($id)
    {
        $perms = [];
        $permissions = $this->model->find($id)->userPermissions()->get();
        
        foreach ($permissions as $item) {
            $perms[$item->id] = $item->slug;
        }

        return $perms;
    }

    /**
     * save role permissions
     * @param $id
     * @param array $perms
     * @return bool
     */
    public function savePermissions($id, $perms = [])
    {
        $user = $this->model->find($id);
        //$role->attachPermission($perms);
        $user->userPermissions()->sync($perms);

        return true;
    }

    /**
     * [modifyBalance 更改余额]
     * @return [type] [description]
     */
    public function modifyBalance($user_id,$money,$type,$note,$frozen_funds=0){
        $user = $this->model->find($user_id);
        $balance = $user->balance+$money;
        $frozen_funds=$user->frozen_funds+$frozen_funds;
        $result = parent::update(['balance'=>$balance,'frozen_funds'=>$frozen_funds], $user_id);
        if($result){
            $now = \Carbon\Carbon::now()->toDateTimeString();
            $data['user_id'] = $user_id;
            $data['money'] = $money;
            $data['balance'] = $balance;
            $data['type'] = $type;
            $data['note'] = $note;
            $data['created_at'] = $now;
            $id = FinancialDetails::insertGetId($data);
            //echo $id;
            if(!$id){
                return ['status'=>0,'msg'=>'写入日志失败'];
            }
            return ['status'=>1,'msg'=>'更新金额成功！'];
        }
        return ['status'=>0,'msg'=>'更新金额失败！'];
    }

}
